﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using FD.RemoteAssistant.Core.Extensions;

namespace FD.RemoteAssistant.Entities.Extensions
{
    /*
     * CreatedOn: 2018-05-16
     * CreatedBy: Jackie Lee(天宇遊龍)
     */
    public static class ObjExtension
    {
        public static IList<DataColumnItem> ToDataColumnItems(this Type type)
        {
            var res = new List<DataColumnItem>();
            if (type == null)
            {
                return res;
            }

            var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            DataColumnItem dataColumnItem;
            string text = string.Empty, dataName = string.Empty;
            DataColumnType dataColumnType = DataColumnType.Text;
            int width = 100;
            foreach (var info in props)
            {
                var caDataColumn = info.GetCustomAttribute<DataColumnAttribute>();
                dataName = info.Name;
                dataColumnItem = new DataColumnItem
                {
                    Name = info.Name
                };
                if (caDataColumn != null)
                {
                    text = caDataColumn.Text;
                    dataName = caDataColumn.DataName;
                    dataColumnType = caDataColumn.DataColumnType;
                    width = caDataColumn.Width;
                    dataColumnItem.IsRequired = caDataColumn.IsRequired;
                    dataColumnItem.ErrMessage = caDataColumn.ErrMessage;
                    dataColumnItem.SortIndex = caDataColumn.SortIndex;
                }

                dataColumnItem.Text = text.IsNullOrEmpty() ? info.Name : text;
                dataColumnItem.DataName = dataName.IsNullOrEmpty() ? info.Name : dataName;
                dataColumnItem.DataColumnType = dataColumnType;
                dataColumnItem.Width = width > 0 ? width : 100;
                res.Add(dataColumnItem);
            }

            return res;
        }

        public static string ToString(this RemoteSetting remoteSetting)
        {
            return $"{remoteSetting.Domain},{remoteSetting.Server},{remoteSetting.UserName},{remoteSetting.Password},{remoteSetting}";
        }
    }
}
